<template>
	<a-range-picker v-model:value="newValue" :show-time="newShowTime" @change="handleChange" />
</template>

<script setup>
import { defineProps, defineEmits, watch } from 'vue'
import { ref, inject } from 'vue'
const dayjs = inject('dayjs')
const props = defineProps({
  value: {
    type: null,
    default: null,
  },
	startTime: {
    type: null,
    default: null,
  },
	endTime: {
    type: null,
    default: null,
  },
  placeholder: {
    type: String,
    default: '请选择',
  },
  width: {
    type: String,
    default: '',
  },
	picker: {
		type: String,
		default: 'date'	
	},
	showTime: {
		type: Boolean,
		default: false
	}
	
})
const newValue = ref()
const newShowTime = ref(false)
const init = () => {
	if (props.showTime || props.picker == 'datetime') newShowTime.value = true
	let v = null
	if (props.value) v = props.value
	if (props.startTime && props.endTime) v = [props.startTime, props.endTime]
	if (!v) return newValue.value = null
	switch (props.picker) {
		case 'year':
			newValue.value = [dayjs(`${v[0]}/01`), dayjs(`${v[1]}/01`)]
			break
		default:
			// date month week
			newValue.value = [dayjs(`${v[0]}`), dayjs(`${v[1]}`)]
			break
	}
}
init()
watch([() => props.value, () => props.startTime, () => props.endTime], ([value, startTime, endTime]) => {
	init()
})
const emit = defineEmits(['update:value', 'update:startTime', 'update:endTime'])
const handleChange = (date) => {
	console.log(date, '???')
  // date | week | month | quarter | year
	let formatObj = {
		date: 'YYYY-MM-DD',
		datetime: 'YYYY-MM-DD HH:mm:ss',
		month: 'YYYY-MM',
		week: 'MM-DD',
		year: 'YYYY'
	}
  emit('update:startTime', date ? date[0].format(formatObj[props.picker] || 'YYYY-MM-DD') : null) 
  emit('update:endTime', date ? date[1].format(formatObj[props.picker] || 'YYYY-MM-DD') : null)
  emit('update:value', date ? [date[0].format(formatObj[props.picker] || 'YYYY-MM-DD'), date[1].format(formatObj[props.picker] || 'YYYY-MM-DD')] : null)
}
</script>